# -*- coding: utf-8 -*-
import json
import os


IflyModelDict = {}
IflyModelDictVer = {}


def addIflyModelDict(projectName: str):
    global IflyModelDict
    global IflyModelDictVer
    filePath = "./project/kedaxunfei/"+projectName+"/iflytekModel.ini"
    # 从文件中解析JSON数据
    with open(filePath, 'r', encoding='utf-8') as file:
        # TODO::增加内容校验
        content = file.read()
        obj = content.split('####')
        if len(obj) != 2:
            return -1

        IflyModelDictVer[projectName] = obj[0]
        iflyModelDate = json.loads(obj[1])
        IflyModelDict[projectName] = iflyModelDate
    return 0


def delIflyModelDict(projectName: str):
    global IflyModelDict
    global IflyModelDictVer
    if projectName in IflyModelDict:
        del IflyModelDict[projectName]
    if projectName in IflyModelDictVer:
        del IflyModelDictVer[projectName]


def getIflyModelDict(projectName: str):
    global IflyModelDict
    if projectName in IflyModelDict:
        return IflyModelDict[projectName]
    else:
        return None


def setIflyModelDict(projectName: str, key: str, unit: dict):
    global IflyModelDict
    if projectName in IflyModelDict:
        units = IflyModelDict[projectName]
        for i in range(len(IflyModelDict[projectName])):
            if units[i]['key'] == key:
                units[i] = unit
                IflyModelDict[projectName] = units
                # 更新文件
                saveIflytekModel(projectName)
                return 0
    return -1


def saveIflytekModel(projectName: str):
    global IflyModelDict
    filePath = "./project/kedaxunfei/" + projectName + "/iflytekModel.ini"
    content = 'V1.0####' + json.dumps(IflyModelDict[projectName])
    # 打开文件并清空内容，然后写入新的内容
    with open(filePath, "w", encoding="utf-8") as file:
        file.write(content)
        return 0
    return -1


def getIflyModelDictVer(projectName: str):
    global IflyModelDictVer
    if projectName in IflyModelDictVer:
        return IflyModelDictVer[projectName]



